package com.songqintuan.platform.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

import net.sf.cglib.beans.BeanCopier;

import com.songqintuan.common.constant.GlobalConstants;
import com.songqintuan.common.util.MessageFactory;
import com.songqintuan.common.util.SpringFacesUtil;
import com.songqintuan.common.util.ValidatorUtil;
import com.songqintuan.model.po.AuthorityResources;
import com.songqintuan.model.po.AuthorityRole;
import com.songqintuan.model.po.RoleResource;
import com.songqintuan.model.po.RoleResource;
import com.songqintuan.model.vo.AuthorityRoleVo;
import com.songqintuan.persist.service.hibernate.IAuthorityResourcesService;
import com.songqintuan.persist.service.hibernate.IAuthorityRoleService;
import com.songqintuan.persist.service.hibernate.IRoleResourceService;
import com.songqintuan.persist.service.hibernate.IRoleResourceService;
import com.songqintuan.platform.base.IManagePojoPageBean;
import com.songqintuan.platform.base.ManagePojoPageBean;
import com.songqintuan.platform.common.constant.PlatformConstants;
import com.songqintuan.platform.common.constant.PlatformSpringBeanConstants;
import com.songqintuan.platform.page.AuthorityRolePage;
import com.songqintuan.platform.tree.ResourceDTree;
import com.songqintuan.platform.util.EntityDataUtil;



@ManagedBean(name="manageAuthorityRolePage")
@SessionScoped
public class ManageAuthorityRolePageBean extends ManagePojoPageBean implements IManagePojoPageBean, Serializable {

	private static final long serialVersionUID = 5054087821033164829L;
	
	private AuthorityRolePage page;
	
	private AuthorityRoleVo view;
	private AuthorityRoleVo edit;
	//分配资源
	private String currentRoleId;
	private String currentRoleName;
	private ResourceDTree resTree;
	private List<AuthorityResources> roleResources = new ArrayList<AuthorityResources>();

	public AuthorityRolePage getPage() {
		return page;
	}

	public void setPage(AuthorityRolePage page) {
		this.page = page;
	}

	public AuthorityRoleVo getView() {
		return view;
	}

	public void setView(AuthorityRoleVo view) {
		this.view = view;
	}

	public AuthorityRoleVo getEdit() {
		return edit;
	}

	public void setEdit(AuthorityRoleVo edit) {
		this.edit = edit;
	}

	public String getCurrentRoleId() {
		return currentRoleId;
	}

	public void setCurrentRoleId(String currentRoleId) {
		this.currentRoleId = currentRoleId;
	}

	public String getCurrentRoleName() {
		return currentRoleName;
	}

	public void setCurrentRoleName(String currentRoleName) {
		this.currentRoleName = currentRoleName;
	}


	public ResourceDTree getResTree() {
		return resTree;
	}

	public void setResTree(ResourceDTree resTree) {
		this.resTree = resTree;
	}

	public List<AuthorityResources> getRoleResources() {
		return roleResources;
	}

	public void setRoleResources(List<AuthorityResources> roleResources) {
		this.roleResources = roleResources;
	}

	public ManageAuthorityRolePageBean(){
		
		AuthorityRole obj = new AuthorityRole();
		page = new AuthorityRolePage(1,PlatformConstants.DEFAULT_ONE_PAGE_NUMBER,obj);
		page.getPageDatas();

	}

	public String selectPageNo() {
		String result = null;
		String pageNo = (String) SpringFacesUtil.getRequestParameter("pageNo");
		if (null != this.getPage().getPageNo()) {
			if (this.getPage().getPageNo().intValue() == Integer.valueOf(pageNo).intValue()) {
				return result;
			}
		}
		this.getPage().setPageNo(Integer.valueOf(pageNo).intValue());
		this.getPage().getPageDatas();
		return result;
		
	}
	public String viewAction(){
		String result = null;
		clearErrorMessages();
		IAuthorityRoleService<AuthorityRole,String> objService = (IAuthorityRoleService<AuthorityRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_ROLE_SERVICE_BEAN_NAME);
		objService.setEntityClass(AuthorityRole.class);
		objService.setPKClass(String.class);
		String objId= (String) SpringFacesUtil.getRequestParameter("objId");
		AuthorityRole obj = objService.findById(objId);
		AuthorityRoleVo objVo =new AuthorityRoleVo();
		BeanCopier copyHere = BeanCopier.create(AuthorityRole.class, AuthorityRoleVo.class, false);
		copyHere.copy(obj, objVo, null);
		this.setAction(PlatformConstants.ACTION_VIEW_TYPE);
		this.setView(objVo);
		return result;
	}
	public String editAction(){//get data
		String result = null;
		clearErrorMessages();
		IAuthorityRoleService<AuthorityRole,String> objService = (IAuthorityRoleService<AuthorityRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_ROLE_SERVICE_BEAN_NAME);
		objService.setEntityClass(AuthorityRole.class);
		objService.setPKClass(String.class);
		String objId= (String) SpringFacesUtil.getRequestParameter("objId");
		AuthorityRole obj = objService.findById(objId);
		AuthorityRoleVo objVo =new AuthorityRoleVo();
		BeanCopier copyHere = BeanCopier.create(AuthorityRole.class, AuthorityRoleVo.class, false);
		copyHere.copy(obj, objVo, null);
		this.setAction(PlatformConstants.ACTION_EDIT_TYPE);
		this.setEdit(objVo);
		return result;
	}
	public String viewToEditAction() {
		String result = null;
		clearErrorMessages();
		this.setEdit(this.getView());
		this.setView(null);
		this.setAction(PlatformConstants.ACTION_EDIT_TYPE);
		return result;
	}
	public String updateAction(){
		String result = null;
		try {
			this.clearErrorMessages();
			validator(this.getErrorMessages(),this.getEdit());
			if (!(this.getErrorMessages().isEmpty())) {
				return null;
			}
			IAuthorityRoleService<AuthorityRole,String> objService = (IAuthorityRoleService<AuthorityRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_ROLE_SERVICE_BEAN_NAME);
			objService.setEntityClass(AuthorityRole.class);
			objService.setPKClass(String.class);
			AuthorityRole obj = objService.findById(this.getEdit().getId());
			obj.setName(this.getEdit().getName());
			obj.setRemark(this.getEdit().getRemark());
			obj.setSort(this.getEdit().getSort());
			//设置通用的修改数据属性 修改时间和修改人
			EntityDataUtil<AuthorityRole,String> currUtil = new EntityDataUtil<AuthorityRole,String>();
			currUtil.setModifyPropertyValue(obj);
			//end
			//按name查找，如果有提示已存在，不能保存
			AuthorityRole theObj = objService.findUniqueBy("name", this.getEdit().getName());
			if (null != theObj && !(theObj.getId().equals(this.getEdit().getId())) ) {
				String hasExistErrorN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"role.has.exist.error.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.getErrorMessages().add(hasExistErrorN18);
				return result;
			} else{//修改时名称不重复，可以修改
				objService.saveOrUpdate(obj);
			}
		}catch (Exception e) {
			String updateErrorN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"update.data.version.not.same.error.message", FacesMessage.SEVERITY_ERROR).getDetail();
			this.setEditDataInPageFlag(false);
			this.getErrorMessages().add(updateErrorN18);
			return result;
		} finally {
            //do nothing;//关闭session的时候还会报，并且在session那里抓取了所有的Exception。
        }
		return result;
	}
	
	public String preCreateAction(){
		String result = null;
		clearErrorMessages();
		this.setAction(PlatformConstants.ACTION_NEW_TYPE);
		AuthorityRoleVo objVo =new AuthorityRoleVo();
		this.setEdit(objVo);
		return result;
	}
	
	public String saveAction(){//create new
		String result = null;
		clearErrorMessages();
		validator(this.getErrorMessages(),this.getEdit());
		if (!(this.getErrorMessages().isEmpty())) {
			return null;
		}
		IAuthorityRoleService<AuthorityRole,String> objService = (IAuthorityRoleService<AuthorityRole,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_ROLE_SERVICE_BEAN_NAME);
		objService.setEntityClass(AuthorityRole.class);
		objService.setPKClass(String.class);
		if (null != this.getEdit() && !("".equals(this.getEdit().getName())) ) {
			AuthorityRole theObj = objService.findUniqueBy("name", this.getEdit().getName());//
			if (null != theObj) {
				String hasExistErrorN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"role.has.exist.error.message", FacesMessage.SEVERITY_ERROR).getDetail();
				this.getErrorMessages().add(hasExistErrorN18);
			}
		}
		if (!(this.getErrorMessages().isEmpty())) {
			return null;
		}
		AuthorityRole newObj = new AuthorityRole();
		BeanCopier copyHere = BeanCopier.create(AuthorityRoleVo.class, AuthorityRole.class, false);
		copyHere.copy(this.getEdit(), newObj, null);
		//设置通用的修改数据属性 修改时间和修改人
		try {
			EntityDataUtil<AuthorityRole,String> currUtil = new EntityDataUtil<AuthorityRole,String>();
			currUtil.setCreatePropertyValue(newObj);
		}catch (Exception e) {
			return result;
		} finally {
            //do nothing;//关闭session的时候还会报，并且在session那里抓取了所有的Exception。
        }
		//end
		objService.save(newObj);
		return result;
	}
	public String refreshPageAction(){
		String result = null;
		this.getPage().getPageDatas();
		return result;
	}
	public String searchPageAction(){
		this.getPage().getPageDatas();
		this.setAction(PlatformConstants.ACTION_SEARCH_TYPE);
		this.setEdit(null);
		this.setView(null);
		return null;
	}
	public String loadRoleResourceAction(){
		String result = null;
		String objId= (String) SpringFacesUtil.getRequestParameter("objId");
		String name= (String) SpringFacesUtil.getRequestParameter("name");
		this.setCurrentRoleId(objId);
		this.setCurrentRoleName(name);
		this.setAction("ALLOCATE");
		//获取角色资源树
		ResourceDTree newTree = new ResourceDTree();
		newTree.getCheckBoxResource(objId);
		this.setResTree(newTree);
		
		/*IAuthorityResourcesService<AuthorityResources, Long> authorityResourcesService = (IAuthorityResourcesService<AuthorityResources, Long>) SpringFacesUtil
				.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_RESOURCES_SERVICE_BEAN_NAME);
		authorityResourcesService.setEntityClass(AuthorityResources.class);
		authorityResourcesService.setPKClass(Long.class);
		List<AuthorityResources> resources = authorityResourcesService.getAll(
				"sort", GlobalConstants.ORDER_BY_ASC_TRUE);
		IRoleResourceService<RoleResource, String> roleResourceService = (IRoleResourceService<RoleResource, String>) SpringFacesUtil
				.getSpringBean(PlatformSpringBeanConstants.ROLE_RESOURCE_SERVICE_BEAN_NAME);
		roleResourceService.setEntityClass(RoleResource.class);
		roleResourceService.setPKClass(String.class);
		List<RoleResource> roleResources = roleResourceService.findBy("roleId", objId);
		operateFor(resources,roleResources);
		this.setRoleResources(resources);*/
		return result;
	}
	private void operateFor(List<AuthorityResources> treeInfoList, List<RoleResource> roleResources){
		AuthorityResources treeInfo = null;
		Map<Long,RoleResource> roleResourceMap = new HashMap<Long,RoleResource>();
		if (null != roleResources && !(roleResources.isEmpty())) {
			Iterator<RoleResource> it = roleResources.iterator();
			RoleResource roleResource = null;
			while (it.hasNext()) {
				roleResource = it.next();
				roleResourceMap.put(roleResource.getResourceId(), roleResource);
			}
		}
		if (null != treeInfoList && !(treeInfoList.isEmpty())) {
			boolean checked = false;
			for (int i = 0; i < treeInfoList.size(); i++) {
				treeInfo = (AuthorityResources) treeInfoList.get(i);
				if (null != roleResourceMap.get(treeInfo.getId())) {
					checked = true;
				} else {
					checked = false;
				}
				treeInfo.setChecked(checked);
			}
		}
	}
	public String allocateRoleResourceAction(){
		String result = null;
		String resourceStr= (String) SpringFacesUtil.getRequestParameter("resourceStr");
		IRoleResourceService<RoleResource,String> objService = objService = (IRoleResourceService<RoleResource,String>)SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.ROLE_RESOURCE_SERVICE_BEAN_NAME);
		objService.setEntityClass(RoleResource.class);
		objService.setPKClass(String.class);
		//删除当前用户角色关联
		if (null != this.getCurrentRoleId() && !("".equals(this.getCurrentRoleId()))) {
			List<RoleResource> roleResources = objService.findBy("roleId", this.getCurrentRoleId());
			for (RoleResource roleRes:roleResources) {
				objService.removeById(roleRes.getId());
			}
		}
		//保存新的用户角色关联
		if (!(resourceStr.isEmpty())) {
			RoleResource newObj = null;
			String[] resources = resourceStr.split(",");
			for (int i=0;i<resources.length;i++) {
				if (!(resources[i].isEmpty())) {
					newObj = new RoleResource();
					newObj.setRoleId(this.getCurrentRoleId());
					newObj.setResourceId(new Long(resources[i]));
					try {
						EntityDataUtil<RoleResource,String> currUtil = new EntityDataUtil<RoleResource,String>();
						currUtil.setCreatePropertyValue(newObj);
					}catch (Exception e) {
						return result;
					} finally {
			            //do nothing;//关闭session的时候还会报，并且在session那里抓取了所有的Exception。
			        }
					//save
					objService.save(newObj);
				}
			}
			
		}
		this.setAction(PlatformConstants.ACTION_EMPTY_TYPE);
		return result;
	}
	private void validator(List<String> errorMessages,AuthorityRoleVo eidt){
		String nameLabelN18 = MessageFactory.getMessage(PlatformConstants.USER_BUNDLE_NAME,"role.name.display", FacesMessage.SEVERITY_ERROR).getDetail();
		ValidatorUtil.EmptyValidatorForInput(errorMessages, edit.getName(), nameLabelN18);		
	}
}
